import 'package:family_expense/features/authentication/widgets/account_register.dart';
import 'package:family_expense/features/authentication/widgets/quick_login.dart';
import 'package:family_expense/main_view.dart';
import 'package:family_expense/shared/services/data_initialization.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

/// IMPORTANT!!!
/// Even we do not use [setState] method here we still need the [StatefulWidget].
/// Because [Form] and [TextFormField] work with [StatefulWidget] only.
/// Otherwise once you tap on a [TextFormField] the keyboard closes after it opens right away.
class PasswordLogin extends StatefulWidget {
  const PasswordLogin({super.key, this.redirectRoute});

  final Widget? redirectRoute;

  @override
  State<PasswordLogin> createState() => _PasswordLoginState();
}

class _PasswordLoginState extends State<PasswordLogin> {
  // IMPORTANT!!!
  // DO NOT CREATE THE KEY IN THE BUILD METHOD OR IN A [StatelessWidget]. OTHERWISE THE [TextFormField] WILL LOST FOCUS ONCE YOU TAP ON IT.
  // Creates a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool _showPassword = false;

  late String _username;
  late String _password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: _buildForm());
  }

  /// Builds the input form.
  Widget _buildForm() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const SizedBox(height: 80.0),
            SizedBox(
              height: 100.0,
              child: Image.asset('assets/images/logo.png'),
            ),
            const SizedBox(height: 20.0),
            Text(
              'Family Expense',
              style: Theme.of(context).textTheme.titleLarge,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 40.0),
            AsyncInitTextFormField(
              asyncInitialValue: AuthStateService.instance.currentUsername,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintText: '请输入手机号',
                prefixIcon: Icon(Icons.phone_android),
              ),
              validator: (value) {
                return FormTextFieldValidator(
                  '手机号',
                  value,
                  patterns: [
                    ValidatorPattern(
                      RegularExpressionPattern.checkMobilePhoneNumber,
                      '请输入正确格式的手机号',
                      matchCheck: false,
                    ),
                  ],
                ).validate();
              },
              onSaved: (value) => _username = value!,
            ),
            const SizedBox(height: 20.0),
            TextFormField(
              obscureText: !_showPassword,
              decoration: InputDecoration(
                hintText: '请输入密码',
                prefixIcon: const Icon(Icons.lock_open),
                suffixIcon: GestureDetector(
                  onTap: () {
                    if (mounted) {
                      setState(() => _showPassword = !_showPassword);
                    }
                  },
                  child: Icon(
                    _showPassword ? Icons.visibility_off : Icons.visibility,
                    semanticLabel: _showPassword ? '显示密码' : '隐藏密码',
                  ),
                ),
              ),
              validator: (value) {
                return FormTextFieldValidator(
                  '密码',
                  value,
                  minLength: User.passwordMinLength,
                  maxLength: User.passwordMaxLength,
                ).validate();
              },
              onSaved: (value) => _password = value!,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  child: const Text('忘记密码？'),
                  onPressed: () => showToast('因本系统没有预算引入付费短信功能，请联系管理员重置密码。'),
                ),
                TextButton(
                  child: const Text('注册账号'),
                  onPressed: () =>
                      NavigatorHelper.push(context, const AccountRegister()),
                ),
              ],
            ),
            Container(
              padding: const EdgeInsets.only(top: 20.0),
              height: 60.0,
              child: PressStatusButton(
                onPressed: _login,
                disabledChild: const Text(
                  '正在登录',
                  style: TextStyle(fontSize: 20.0),
                ),
                child: const Text('登  录', style: TextStyle(fontSize: 20.0)),
              ),
            ),
            // shared_preferences package is not compatible with FlutterFragmentActivity which is needed by local_auth package.
            // By now we only can disable the features rely on local_auth package.
            Container(
              padding: const EdgeInsets.only(top: 20.0),
              height: 60.0,
              child: TextButton(
                child: const Text('快速登录'),
                onPressed: () => NavigatorHelper.push(
                  context,
                  QuickLogin(redirectRoute: widget.redirectRoute),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Login action.
  Future<void> _login() async {
    // Validate returns true if the form is valid, or false otherwise.
    if (!_formKey.currentState!.validate()) {
      showToast('请正确填写各项信息');
      return;
    }

    // Saves current form.
    _formKey.currentState!.save();

    // Starts to login.
    final res = await AuthService().login(_username, _password);

    // Checks on the response.
    if (res['accessToken'] != null) {
      // Converts the server data to user instance.
      final user = User.fromJson(res);

      final authStateService = AuthStateService.instance;

      // Saves the user data retrieved from server.
      authStateService.saveUserInfo(user);

      // Converts the server data to token instance.
      final token = Token.fromServerJson(res);

      // Saves the token data retrieved from server.
      await TokenService.saveToken(token);

      // Checks if current user is in collection. If it is that means current users enabled quick action.
      // We just update the user and token data in the collection just in case the server refreshed the token.
      if (await authStateService.isUserInCollection(user)) {
        authStateService.saveUserToCollection(user);
        TokenService.saveTokenForUserInCollection(user);
      }

      if (mounted) {
        // Shows the overlay when loading the data.
        showInProgressOverlay(context, message: '正在登录');
      }

      // Initializes the system data.
      DataInitialization().init(() {
        // Jumping to new route and the login page will be popped.
        // It can prevent user to go back to the login page by pressing back button.
        // Let [MainView] handle the redirection will make user can go back from target view to [MainView].
        // Otherwise when user goes back from target view it only causes app to exit.
        NavigatorHelper.pushAndRemoveUntil(
          context,
          MainView(redirectRoute: widget.redirectRoute),
          (route) => false,
        );
      });
    }
  }
}
